package com.cp.admin.api.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.StreamUtils;

import java.io.*;

/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2017/09/19 09:59
 */
@Slf4j
public class FileUtils {

    /**
     * 生成本地文件
     * @param str 文件内容
     * @param file 文件路径
     * @param charset 编码格式
     * @return
     */
    public static boolean stringWriteToFile(String str, String file, String charset) {
        try {
            File destFile = new File(file);
            if (!destFile.getParentFile().exists()) {
                System.out.println("目标文件所在目录不存在，准备创建它！");
                if (!destFile.getParentFile().mkdirs()) {
                    System.out.println("创建目标文件所在目录失败！");
                    return false;
                }
            }
            if(!destFile.exists()){
                destFile.createNewFile();
                destFile.setReadable(true, false);
                destFile.setWritable(true, false);
                //destFile.setExecutable(true,false);
            }
            FileOutputStream out = new FileOutputStream(file);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, charset));
            int len = 4096;
            int c = str.length() / len;
            int lef = str.length() % len;
            int index = 0;
            for (int i = 0; i < c;) {
                bw.write(str, index, len);
                ++i;
                index = i * len;
            }
            bw.write(str, index, lef);
            bw.flush();
            bw.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("写文件错误："+e.getMessage());
        }
        return false;
    }

    /**
     * 上传文件
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    /**
     * 读文件
     * @param path
     * @return
     */
    public static String readFile(String path) {
        if (path == null || "".equals(path.trim())) return null;

        File file = new File(path);
        BufferedReader reader = null;
        StringBuilder str = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String temp = null;
            while ((temp= reader.readLine()) != null) {
                str.append(temp);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件读取失败，路径为：{}", path);
            throw new RuntimeException("文件读取失败", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return str.toString();
    }

    public static boolean saveFile(String queryData, String filePath) {

        try {
            File destFile = new File(filePath);
            //判断目标文件所在的目录是否存在
            if(!destFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                System.out.println("目标文件所在目录不存在，准备创建它！");
                if(!destFile.getParentFile().mkdirs()) {
                    System.out.println("创建目标文件所在目录失败！");
                    return false;
                }
            }
            if(!destFile.exists()){
                destFile.createNewFile();
                destFile.setReadable(true, false);
                destFile.setWritable(true, false);
                //destFile.setExecutable(true,false);
            }
            FileOutputStream out = new FileOutputStream(filePath);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "utf-8"));
            int len = 4096;
            int c = queryData.length() / len;
            int lef = queryData.length() % len;
            int index = 0;
            for (int i = 0; i < c;) {
                bw.write(queryData, index, len);
                ++i;
                index = i * len;
            }
            bw.write(queryData, index, lef);
            bw.flush();
            bw.close();
            return true;
        }catch (Exception e){
            System.out.println("写文件错误："+e.getMessage());
        }
        return false;

    }

    //url文件下载
    public static void downLoad(String src_file, String dest_file) throws Throwable {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpget = new HttpGet(src_file);
            httpget.setConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(3*1000)
                    .setConnectTimeout(3*1000)
                    .setSocketTimeout(3*1000)
                    .build());
            try (CloseableHttpResponse response = httpclient.execute(httpget)) {
                org.apache.http.HttpEntity entity = response.getEntity();
                File desc = new File(dest_file);
                File folder = desc.getParentFile();
                folder.mkdirs();
                try (InputStream is = entity.getContent();
                     OutputStream os = new FileOutputStream(desc)) {
                    StreamUtils.copy(is, os);
                }
            }catch(Throwable e){
                throw new Throwable(src_file+"文件下载失败......", e);
            }
        }
    }
}
